package com.gangan.controller.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gangan.controller.common.BaseController;
import com.gangan.model.Auth;
import com.gangan.model.Role;
import com.gangan.model.search.AuthSearch;
import com.gangan.model.view.AuthView;
import com.gangan.service.IAuthService;
import com.gangan.service.IRoleService;
import com.gangan.tools.MessageBean;
import com.gangan.tools.StringTools;
import com.gangan.tools.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 前端菜单与权限控制
 */
@Api(description = "*菜单权限控制层")
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {
    @Autowired
    IRoleService roleService;
    @Autowired
    IAuthService authService;

    /**
     * 根据存储在session中的用户信息，查询该用户角色，并将数据存入
     * @return
     */
    @GetMapping
    @ApiOperation(value="获取前端菜单权限树", notes="根据当前登录的用户角色查询前端菜单与权限")
    public MessageBean view(){
        //当前用户不是超级管理员时，通过当前用户的角色id查询角色。
        Map<String,Object> map = new HashMap<>();
        //根据角色内的authids查询数据
        List<Auth> auths = authService.resultAuthByRoleId(resultUser().getRoleId());
        //对刚查询的数据进行过滤，将按钮级别的数据过滤掉，传入树构造中
        List<AuthView> menus = TreeUtil.buildTree(auths.stream()
                .filter(auth-> !AuthView.AUTH_TYPE_BTN.equals(auth.getAuthType()))
                .sorted(Comparator.comparingInt(Auth::getSort))
                .collect(Collectors.toList()),0);
        map.put("menu",menus);
        //将查询出来的数据进行过滤，并输出按钮级别的权限。
        map.put("permission",auths.stream()
                .filter(auth-> AuthView.AUTH_TYPE_BTN.equals(auth.getAuthType()))
                .map(Auth::getPermission)
                .collect(Collectors.toList()));
        return resultSuccess(map);
    }

    /**
     * 菜单权限列表
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiOperation(value="返回权限树", notes="返回权限树")
    public MessageBean muneTreeView(){
        Role role = roleService.getById(resultUser().getRoleId());
        List<Auth> menus = authService.list();
        List<Integer> ids = new ArrayList();
        //遍历判断是否角色存储的ids内是否包含以下菜单
        menus.stream().forEach((auth) ->{
            if(role.getRoleAuthIds().indexOf(auth.getAuthId()) > -1){
                ids.add(auth.getAuthId());
            }
        });
        return resultSuccess(TreeUtil.buildTree(menus,0));
    }

    /**
     * 菜单权限列表
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value="新增前端菜单", notes="新增前端菜单")
    public MessageBean authAdd(Auth view){
        return authOperaction(view);
    }
    /**
     * 菜单权限列表
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation(value="修改前端菜单", notes="修改前端菜单")
    public MessageBean authUpdate(Auth view){
        if(null == view.getAuthId()||view.getAuthId()<= 0 ){
            return resultFailed("请选择正确且有效的菜单");
        }else if(null==authService.getById(view.getAuthId())){
            return resultFailed("请选择正确且有效的菜单");
        }
        return authOperaction(view);
    }

    /**
     * 菜单权限列表
     * @return
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    @ApiOperation(value="删除前端菜单", notes="删除前端菜单")
    public MessageBean authDelete(Integer authId){
        Auth auth = authService.getById(authId);
        if(null == auth){
            return resultFailed("请选择正确且有效的菜单");
        }else if(CollectionUtils.isNotEmpty(authService.list(Wrappers.<Auth>query().lambda().eq(Auth::getAuthPid,authId)))){
            return resultFailed("当前菜单含子菜单,不可删除.");
        }else if(!authService.removeById(authId)){
            return resultFailed();
        }
        return  resultSuccess();
    }

    /**
     * 前端菜单新增/修改操作
     * @param view
     * @return
     */
    public MessageBean authOperaction(Auth view){
        if(null!=view.getAuthId()&&!authService.updateById(view)){
            return resultFailed();
        }else if(null==view.getAuthId()&&!authService.save(view)){
            return resultFailed();
        }
        return resultSuccess();
    }
}
